package com.inepex.inechart.client.displayengine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeMap;

public class LayerGroup extends Layer{

	protected Comparator<Layer> sorter = new Comparator<Layer>() {

		@Override
		public int compare(Layer one, Layer other) {
			if(one.layerPosition == other.layerPosition){
				return ((Integer)one.zIndex).compareTo(other.zIndex);
			}
			else if(one.layerPosition == LayerPosition.always_on_bottom){
				return -1;
			}
			else{
				return 1;
			}
		}
	};

	protected ArrayList<Layer> children;
	protected TreeMap<String, Layer> namedLayers;

	protected LayerGroup(LayerGroup parent) {
		super(parent);
		children = new ArrayList<Layer>();
		namedLayers = new TreeMap<String, Layer>();
	}

	public LayerGroup createLayerGroup(){
		LayerGroup lg = new LayerGroup(this);
		children.add(lg);
		return lg;
	}

	public Layer createLayer(){
		Layer l = new Layer(this);
		children.add(l);
		return l;
	}
	
	public Layer createLayer(String name){
		Layer layer = createLayer();
		namedLayers.put(name, layer);
		return layer;
	}
	
	public LayerGroup createLayerGroup(String name){
		LayerGroup lg = createLayerGroup();
		namedLayers.put(name, lg);
		return lg;
	}
	
	public Layer getNamedLayer(String name){
		return namedLayers.get(name);
	}
	
	public LayerGroup getNamedLayerGroup(String name){
		Layer layer = getNamedLayer(name);
		if(layer != null && layer instanceof LayerGroup){
			return (LayerGroup) layer;
		}
		return null;
	}
	
	public void removeLayer(Layer layer){
		children.remove(layer);
	}

	protected ArrayList<Layer> getSortedChildren(){
		ArrayList<Layer> sortedChildren = new ArrayList<Layer>(children);
		Collections.sort(sortedChildren, sorter);
		for (int i=0;i<sortedChildren.size();i++) {
			Layer child = sortedChildren.get(i);
			if(child instanceof LayerGroup){
//				sortedChildren.remove(i); //should we exclude a layergroup's widgets?
				ArrayList<Layer> childsSortedChildren = ((LayerGroup) child).getSortedChildren();
				for (int j=0;j<childsSortedChildren.size();j++) {
					sortedChildren.add(i+j, childsSortedChildren.get(j));
				}
			}
		}
		return sortedChildren;
	}

	@Override
	public void setOpacity(double opacity) {
		for (Layer child : children) {
			//			if(child instanceof LayerGroup){
			child.setOpacity(opacity);
			//			}
		}
		super.setOpacity(opacity);
	}
	
//	@Override
//	public ArrayList<Widget> getWidgets() {
//		return null;
//	}
}
